package fit.glike.net.util;

import cn.hutool.json.JSONUtil;
import fit.glike.net.domain.MailConf;
import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

@Slf4j
public class MailUtil {

    // QQ邮箱的SMTP服务器地址为: smtp.qq.com
    private static String hostTemp = "smtp.139.com";
    // 端口一般是465或者587
    private static String portTemp = "465";
    // 你的QQ邮箱用户名
    private static String userNameTemp = "rysoft@139.com";
    // 你的QQ邮箱密码（记得使用生成的授权码而不是密码本身）
    private static String passwordTemp = "53c162658dfe20011600";
    // 收件人邮箱地址
    private static String toAddressTemp = "gguochen@foxmail.com";

    private static MailConf getMailConf() {
        try {
            String jsonFile = "/home/sophia/application/netConf/conf/mailConf.json";
            // 读取文件内容
            String jsonContent = new String(Files.readAllBytes(Paths.get(jsonFile)));
            log.info("获取到mailConf.json信息为: {}", jsonContent);
            // 解析JSON
            MailConf mailConf = JSONUtil.toBean(jsonContent, MailConf.class);
            return mailConf;
        } catch (Exception e) {
            log.error("解析mailConf.json出现异常: {}", e.getMessage());
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    public static void sendMail(String subject, String emailBody) {
        try {
            MailConf mailConf = getMailConf();
            if (mailConf == null) {
                log.error("获取邮箱配置异常: {}", mailConf);
                throw new RuntimeException("获取邮箱配置异常");
            }
            log.info("发送邮件通知---start");
            // 设置SMTP服务器属性
            Properties properties = new Properties();
            properties.put("mail.smtp.host", mailConf.getHost());
            properties.put("mail.smtp.port", mailConf.getPort());
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.starttls.enable", "true"); // 对于QQ邮箱，需要使用SSL
            properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

            // 新建一个认证器
            Authenticator authenticator = new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(mailConf.getUserName(), mailConf.getPassword());
                }
            };

            // 新建会话
            Session mailSession = Session.getInstance(properties, authenticator);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            message.setFrom(new InternetAddress(mailConf.getUserName()));
            // 设置收件人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailConf.getToAddress()));

            // 设置邮件主题
            message.setSubject(subject);
            // 设置邮件内容
            // 设置邮箱名片签名
            String htmlBody = "<br><br><br><h2 style=\"color:#75878a;font-size:18px\"><a href=\"https://buss.glike.top\">燃源高端定制</a></h2><p style=\"font-size:14px\">登高望远不是为了被整个世界看到，而是为了看到整个世界。<br><a href=\"mailto:rysoft@139.com\">rysoft@139.com</a></p>";

            String messageContent = String.format("%s \n\n\n%s", emailBody, htmlBody);
            message.setText(messageContent, "UTF-8", "html");
            // 发送邮件
            Transport.send(message);
            log.info("发送给{} 的通知邮件成功!", mailConf.getToAddress());
        } catch (MessagingException e) {
            log.error("邮件发送异常: {}", e.getMessage());
            log.error(e.getMessage(), e);
        }
    }

}
